import axios from "axios"
import store from "@/plugins/store"
import { Toast } from "vant"

let defaultConfig = {
  baseURL: process.env.VUE_APP_URE,
  url: "",
  method: "post",
  responseType: "json",
  headers: {},
  params: {},
  data: {},
  timeout: 10000,
  statusCode: () => { },
  complete: () => {
    // console.log('No completed callback function！');
  },
  success: () => {
    console.log('No successful callback function！');
  },
  fail: () => {
    console.log('No failed callback function！');
  },
}

export default (parameter = {}) => {
  let config = { ...defaultConfig, ...parameter };
  const instance = axios.create({
    baseURL: config.baseURL,
    url: config.url,
    method: config.method,
    responseType: config.responseType,
    headers: config.headers,
    params: config.params,
    data: config.data,
    timeout: config.timeout,
    validateStatus: function (status) {
      config.statusCode(status);

      if (status === 500) {
        Toast.clear();
        Toast("服务器内部错误!");
      } else if (status === 404) {
        Toast.clear();
        Toast("请求地址不存在!");
      }

      return status === 200 || status === 204
    }
  });

  store.commit('axiosRequest', true);
  instance().then((res) => {
    store.commit('axiosRequest', false);
    config.complete();

    const { code, data, msg } = res.data;

    // 返回数据预处理
    if (code == 10000 || code === 0) {
      // 正常请求
      try {
        config.success(data);
      } catch {
        Toast.clear();
        Toast('请求数据格式异常!');
      }
    } else if (false) {
      // 错误码处理
    } else {
      Toast.clear();
      Toast(msg);
    }

  }).catch((err) => {
    store.commit('axiosRequest', false);
    config.complete();

    Toast.clear();
    if (e.code === 'ECONNABORTED' && e.message.indexOf('timeout') !== -1 && !e.config._retry) {
      Toast("请求超时!");
    }
    config.fail(e);

  });

}